#!/bin/bash

# Copyright (c) 2024 Huawei Device Co., Ltd.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

DIR=$PWD
WORK_ROOT=$PWD

function prepare_env() {
    export JAVA_HOME=$DIR/flutter_env/jdk-17.0.8

    export PUB_HOSTED_URL=https://pub.flutter-io.cn
    export FLUTTER_STORAGE_BASE_URL=https://flutter-ohos.obs.cn-south-1.myhuaweicloud.com

    export FLUTTER_HOME=$DIR/flutter_flutter
    export PATH=$JAVA_HOME/bin:$FLUTTER_HOME/bin:$PATH

    export TOOL_HOME=$DIR/command-line-tools
    export DEVECO_SDK_HOME=$TOOL_HOME/sdk
    export NODE_HOME=$DIR/flutter_env/node-v16.14.2-linux-x64
    export PATH=$TOOL_HOME/ohpm/bin:$TOOL_HOME/hvigor/bin:$NODE_HOME/bin:$PATH
}

function get_project_name() {
    # 默认构建项目路径
    DEFALUT_PROJECT='ohos/http_test'
    local diff_url=$1.diff
    local diff_name=${diff_url##*/}
    local retval=1
    if [ ! -f $diff_name ]
    then
        wget $diff_url
        if [ $? -ne 0 ]
        then
            echo "$DEFALUT_PROJECT"
            reutrn $retval
        fi
    fi
    local diff_str=`cat $diff_name | grep "diff --git"`
    # 匹配a/ohos/开头，/ohos/entry/.* 中间的路径，因为不同项目的目录结构不同
     local regex="a/(.*)/ohos/entry/.*"
    for diff in $diff_str
    do
    local tmp=`echo $diff | grep "/"`
    if [ ! -z "$tmp" ]
    local find=0
    then
        if [[ $tmp =~ $regex ]]; then
            tmp=${BASH_REMATCH[1]}
            echo "$tmp"
            retval=0
            find=1
            break
        fi
    fi
    done
    if [[ $find -eq 0 ]]
    then
        echo "$DEFALUT_PROJECT"
    fi
    return $retval
}
PROJECT=$(get_project_name $1)

function start_compile() {
    #配置环境变量
    prepare_env

    #执行构建
    echo "~项目位置：$PROJECT"
    echo "~引擎位置：$WORK_ROOT"

    flutter doctor -v
    cd ./third_party/flutter/samples/$PROJECT && flutter pub get && rm -rf ./pubspec.lock
    echo "开始构建hap包"
    flutter build hap --target-platform ohos-arm64 --debug

    mv ./ohos/entry/build/default/outputs/default/entry-default-unsigned.hap $WORK_ROOT/hap_out/
}

# shellcheck disable=SC2068
start_compile $@

exit $?

#eof